<template>
  <page-header-wrapper>
    <template v-slot:content>
      <div class="page-header-content">
        <div class="avatar">
          <a-avatar size="large" :src="currentUser.avatar"/>
        </div>
        <div class="content">
          <div class="content-title">
            {{ timeFix }}，{{ user.name }}<span class="welcome-text">，{{ welcome }}</span>
          </div>
        </div>
      </div>
    </template>
    <template v-slot:extraContent>
      <div class="extra-content">
        <div class="stat-item">
          <a-statistic title="项目数" :value="pcount.projectCount" />
        </div>
        <div class="stat-item">
          <a-statistic title="运行管道" :value="pcount.pipelineRunCount"/>
        </div>
        <div class="stat-item">
          <a-statistic title="失败管道" :value="pcount.pipelineRunFailedCount" />
        </div>
      </div>
    </template>

    <div>
      <a-card :body-style="{padding: '24px 32px'}" :bordered="false">
        <div class="table-operator">
          <a-button type="primary" style="margin-right: 0px;">项目</a-button>
          <a-select v-model="query.projectId" style="width: 200px">
            <a-select-option v-for="(item, index) in projectList" :key="index" :value="item.id">{{item.projectName}}</a-select-option>
          </a-select>
          <a-button type="primary" icon="plus" style="margin-left: 75%;" @click="createPipeline">创建管道</a-button>
        </div>
        <Collapse v-model="activeGroupKeys">
          <CollapsePancel :key="item.id" :header="item.groupName" v-for="item in groupPipelineList">
            <div style="padding: 0px 32px">
              <a-list class="demo-loadmore-list" item-layout="horizontal" :data-source="item.pipelineList">
                <a-list-item slot="renderItem" slot-scope="pipeline, index">
                  <a-dropdown slot="actions">
                    <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                      操作 <a-icon type="down" />
                    </a>
                    <a-menu slot="overlay">
                      <a-menu-item>
                        <a href="javascript:;" @click="toEditPipeline(pipeline.id)">编辑</a>
                      </a-menu-item>
                      <a-menu-item v-if="pipeline.status == 0">
                        <a href="javascript:;" @click="deletePipeline(pipeline.id, pipeline.name)">删除</a>
                      </a-menu-item>
                      <a-menu-item v-if="pipeline.status == 2 || pipeline.status == 3">
                        <a href="javascript:;" @click="stopPipeline(pipeline.id, pipeline.name)">停止</a>
                      </a-menu-item>
                      <a-menu-item v-if="pipeline.status == 2 || pipeline.status == 3">
                        <a href="javascript:;" @click="showLogs(pipeline.id)">查看日志</a>
                      </a-menu-item>
                      <a-menu-item v-if="pipeline.status == 2 || pipeline.status == 3">
                        <a href="javascript:;" @click="toView(pipeline.id)">详情</a>
                      </a-menu-item>
                    </a-menu>
                  </a-dropdown>
                  <a-list-item-meta
                    :description="pipeline.description"
                  >
                    <a slot="title">
                      {{ pipeline.name }}
                      <Tag v-if="pipeline.status != 3" :color="statusColor(pipeline.status)">{{convertStatusName(pipeline.status)}}</Tag>
                      <Tag v-if="pipeline.status == 3" :color="statusColor(pipeline.status)"><a @click="showError(pipeline.log)">{{convertStatusName(pipeline.status)}} <a-icon type="alert" /> </a></Tag>
                      <span style="color: #bcbfc3;font-weight: 300;">上次更新时间：<span v-text="pipeline.modifyTime.replace('T', ' ')"></span></span>
                      <span v-text="pipeline.log" style="color: red;margin-left: 20px"></span>
                    </a>
                  </a-list-item-meta>
                  <Tag color="magenta">workers: {{pipeline.workers}}</Tag>
                  <Tag color="green">host: {{pipeline.expectRunHost ? pipeline.expectRunHost : pipeline.actualRunHost}}</Tag>

                </a-list-item>
              </a-list>
            </div>
          </CollapsePancel>
        </Collapse>
      </a-card>
      <a-drawer title="日志信息" width="1200" :visible="showLogFlag" @close="hideLogs">
        <div id="log_div" style="width: 100%;min-height: 800px;border: 1px solid #ccd1d3;background-color: #f5f5f5"></div>
      </a-drawer>
    </div>
  </page-header-wrapper>
</template>

<script>
import { timeFix,getUUID } from '@/utils/util'
import { getProjectCount } from "../../api/monitor";
import { mapState } from 'vuex'
import { PageHeaderWrapper } from '@ant-design-vue/pro-layout'
import { Radar } from '@/components'

import { getRoleList, getServiceList } from '@/api/manage'

import { upload, getVersionList } from '@/api/logstash'
import { getProjectList } from '@/api/logstash_project'
import { queryGroupPipeline } from '@/api/logstash_group'
import { deletePipeline,queryPipeline,stopPipeline,startPipeline } from '@/api/logstash_pipeline'
import { Collapse, Tag } from 'ant-design-vue'
import RoleModal from '../other/modules/RoleModal'

const DataSet = require('@antv/data-set')
const columns = [
  {
    title: '#',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '版本号',
    dataIndex: 'logstash_version'
  },
  {
    title: 'host',
    dataIndex: 'host',
    scopedSlots: { customRender: 'host' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: 'Workplace',
  components: {
    Collapse,
    CollapsePancel: Collapse.Panel,
    PageHeaderWrapper,
    Radar,
    Tag
  },
  data () {
    return {
      timeFix: timeFix(),
      avatar: '',
      user: {},

      projects: [],
      teams: [],

      query:{
        projectId: null
      },
      showList: true,
      dataList: [],
      projectList: [],
      groupPipelineList: [],
      activeGroupKeys: [],
      statusColorMap: {0: "volcano", 1: "lime", 2: "green", 3: "red"},
      statusNameMap: {0: "未运行", 1: "调度中", 2: "运行中", 3: "运行错误"},
      intervalId: null,
      showLogFlag: false,
      socket: null,
      socketPath: "ws://127.0.0.1:8099/llog/",
      logDiv: null,

      pcount: {
        pipelineRunCount: 0,
        pipelineRunFailedCount: 0,
        projectCount: 0
      },
      pipelineList: [],
      errorPipelineList: []
    }
  },
  computed: {
    ...mapState({
      nickname: (state) => state.user.nickname,
      welcome: (state) => state.user.welcome
    }),
    currentUser () {
      return {
        name: 'Serati Ma',
        avatar: 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png'
      }
    },
    userInfo () {
      return this.$store.getters.userInfo
    },

  },
  created () {
    this.user = this.userInfo
    this.avatar = this.userInfo.avatar

    getProjectCount().then(res => {
      console.log(res)
      if(res.code == 200){
        this.pcount = res.data
      }
     })
    this.getProjectList()
  },
  mounted () {
    this.loadData()
    this.queryGroupPipeline()
    this.dataRefreh()
  },
  methods: {
    toView (id) {
      this.$router.push({ path: '/pipeline/view', query: {id: id} })
    },
    createPipeline () {
      this.$router.push({ path: '/pipeline/edit' })
    },
    loadData () {
      const me = this
      getVersionList(this.query).then(res => {
        if (res.code === 200) {
          me.dataList = res.data
        }
      })
    },
    getProjectList () {
      getProjectList().then(res => {
        this.projectList = res.data
        if(this.projectList.length > 0){
          this.query.projectId = this.projectList[0].id
        }else{
          this.$warning({
            title: '重要提示',
            content: '请建立项目',
            onOk: function () {
              me.$router.push({ path: '/data-control/project' })
            }
          });
        }
      })
    },
    queryGroupPipeline () {
      queryGroupPipeline({
        projectId: this.$store.state.project.projectId
      }).then(res => {
        if(res.code == 200){
          this.groupPipelineList = res.data
          if(this.groupPipelineList.length > 0){
            this.activeGroupKeys = [this.groupPipelineList[0].id]
          }
        }
      })
    },
    toEditPipeline (id) {
      this.$router.push({ path: '/pipeline/edit', query: {id: id} })
    },
    deletePipeline (id, name) {
      const me = this
      me.$confirm({
        title: '提示',
        content: '请确认是否删除【' + name + '】管道',
        onOk() {
          deletePipeline(id).then(res => {
            if(res.code == 200){
              me.$message.success('删除成功')
              me.queryGroupPipeline()
            }
          })
        },
        onCancel() {},
      });
    },
    stopPipeline (id, name) {
      const me = this
      me.$confirm({
        title: '提示',
        content: '请确认是否停止【' + name + '】管道',
        onOk() {
          stopPipeline(id).then(res => {
            if(res.code == 200){
              me.$message.success('停止成功')
              me.queryGroupPipeline()
            }else{
              me.$message.error(res.message)
            }
          })
        },
        onCancel() {},
      });
    },
    startPipeline (id, name) {
      const me = this
      me.$confirm({
        title: '提示',
        content: '请确认是否启动【' + name + '】管道',
        onOk() {
          startPipeline(id).then(res => {
            if(res.code == 200){
              me.$message.success('启动成功')
              me.queryGroupPipeline()
            }else{
              me.$message.error(res.message)
            }
          })
        },
        onCancel() {},
      });
    },
    statusColor (status) {
      return this.statusColorMap[status]
    },
    convertStatusName (status) {
      return this.statusNameMap[status]
    },
    dataRefreh() {
      // 计时器正在进行中，退出函数
      if (this.intervalId != null) {
        return;
      }
      // 计时器为空，操作
      this.intervalId = setInterval(() => {
        console.log("刷新" + new Date());
        this.queryGroupPipeline();
      }, 10000);
    },
    sendWebsocket() {
      // 计时器正在进行中，退出函数
      if (this.intervalWebsocketId != null) {
        return;
      }
      // 计时器为空，操作
      this.intervalWebsocketId = setInterval(() => {
        this.socket.send("1")
      }, 1000);
    },
    clearWebsocket() {
      clearInterval(this.intervalWebsocketId)
      this.intervalWebsocketId = null
      if(this.socket){
        this.socket.close()
      }
      this.socket = null
      if(this.logDiv){
        this.logDiv.innerHTML = ''
      }
    },
    // 停止定时器
    clear() {
      clearInterval(this.intervalId); //清除计时器
      this.intervalId = null; //设置为null
    },
    showLogs(pipelineId) {
      this.showLogFlag = true
      this.connWebSocket(pipelineId)
    },
    hideLogs() {
      this.showLogFlag = false
      this.clearWebsocket()
    },
    connWebSocket(pipelineId) {
      this.socket = new WebSocket("ws://127.0.0.1:8099/llog/" + pipelineId + "-" + getUUID())
      this.socket.onopen = this.openWebsocket
      this.socket.onerror = function () {
        console.log("连接错误")
      }
      this.socket.onclose = this.clearWebsocket
      this.socket.onmessage = this.showLogContent
    },
    openWebsocket() {
      this.sendWebsocket()
      this.logDiv = document.getElementById("log_div");
      this.logDiv.innerHTML = ''
    },
    showLogContent(msg) {
      let p = document.createElement("p")
      p.appendChild(document.createTextNode(msg.data))
      this.logDiv.appendChild(p)
    },
    showError(error) {
      this.$error({
        title: '运行错误',
        content: error
      });
    }
  }
}
</script>

<style lang="less" scoped>
  @import "./Workplace.less";

  .project-card-grid {
    margin-left: 10px;
    margin-top: 10px;
  }
  .project-list {

    .card-title {
      font-size: 0;

      a {
        color: rgba(0, 0, 0, 0.85);
        margin-left: 12px;
        line-height: 24px;
        height: 24px;
        display: inline-block;
        vertical-align: top;
        font-size: 14px;

        &:hover {
          color: #1890ff;
        }
      }
    }

    .card-description {
      color: rgba(0, 0, 0, 0.45);
      height: 44px;
      line-height: 22px;
      overflow: hidden;
    }

    .project-item {
      display: flex;
      margin-top: 8px;
      overflow: hidden;
      font-size: 12px;
      height: 20px;
      line-height: 20px;

      a {
        color: rgba(0, 0, 0, 0.45);
        display: inline-block;
        flex: 1 1 0;

        &:hover {
          color: #1890ff;
        }
      }

      .datetime {
        color: rgba(0, 0, 0, 0.25);
        flex: 0 0 auto;
        float: right;
      }
    }

    .ant-card-meta-description {
      color: rgba(0, 0, 0, 0.45);
      height: 44px;
      line-height: 22px;
      overflow: hidden;
    }
  }

  .item-group {
    padding: 20px 0 8px 24px;
    font-size: 0;

    a {
      color: rgba(0, 0, 0, 0.65);
      display: inline-block;
      font-size: 14px;
      margin-bottom: 13px;
      width: 25%;
    }
  }

  .members {
    a {
      display: block;
      margin: 12px 0;
      line-height: 24px;
      height: 24px;

      .member {
        font-size: 14px;
        color: rgba(0, 0, 0, .65);
        line-height: 24px;
        max-width: 100px;
        vertical-align: top;
        margin-left: 12px;
        transition: all 0.3s;
        display: inline-block;
      }

      &:hover {
        span {
          color: #1890ff;
        }
      }
    }
  }

  .mobile {

    .project-list {

      .project-card-grid {
        width: 100%;
      }
    }

    .more-info {
      border: 0;
      padding-top: 16px;
      margin: 16px 0 16px;
    }

    .headerContent .title .welcome-text {
      display: none;
    }
  }

</style>
